const crypt = require("../../utils/crypt");
const authorObj = require("./author");
const jwt = require("../../utils/jwt");

// jwt鉴权中间件（token）
module.exports = function (req, res, next) {
  const { baseUrl, path } = parserUrl(req.url);
  // console.log("baseUrl", baseUrl);
  // console.log("path", path);
  const curAuthor = authorObj[baseUrl]?.list?.find((item) => {
    // console.log("item.path", item.path);
    // console.log("path", path);
    return item.path.test(path) && item.method === req.method;
  });

  // console.log("curAuthor", JSON.stringify(curAuthor));
  if (!curAuthor || !curAuthor.needToken) {
    next();
    return;
  }

  // let { token } = req.cookies;
  // console.log("cookies", req.cookies);
  let token = req.headers.authorization;
  // console.log("token", token);
  if (!token) {
    return hasNoneToken(res);
  }
  token = token.split(" ");
  token = token.length > 1 ? token[1] : token[0];
  // 验证token
  const result = jwt.decryptToken(token);
  // console.log("result", result);
  if (!result) {
    // token验证失败
    return hasNoneToken(res);
  }
  // console.log("result", result);
  req.userId = result.id;
  next();
};

function parserUrl(url) {
  url = url.includes("?") ? url.split("?")[0] : url;
  const arr = url.split("/");
  // console.log("parserUrl", arr);
  return {
    baseUrl: arr.slice(0, 3).join("/"),
    path: ["", ...arr.slice(3)].join("/"),
  };
}

function hasNoneToken(res) {
  res.status(401).json({
    code: 401,
    message: "you have no token to access this api",
  });
}
